package com.study.zookeeper.zkclient;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

public class FirstZKClient {

    private static ZkClient zkClient = null;
    private static String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
    private static int sessionTime = 5000;
    private static String parentPath = "/zk-book";

    public static void main(String[] args) throws InterruptedException {

        zkClient = connectZK();
        String path = "/zlx/test";
        //只需要注册一次，就会一直生效
        zkClient.subscribeChildChanges(parentPath, new ChildrenChangesListener());
        //注册
        zkClient.subscribeDataChanges(parentPath, new ChildrenDataChangeListener());
        if(!zkClient.exists(parentPath)){
            System.out.println(parentPath + " does not exitst zkClient");
            zkClient.createPersistent(parentPath);
        }

        //更新数据
        zkClient.writeData(parentPath, "123456");
        zkClient.readData(parentPath);
        Thread.sleep(1000);
        System.out.println(zkClient.getChildren(parentPath));
        Thread.sleep(1000);
        zkClient.createPersistent(parentPath + "/c1");
        List<String> children = zkClient.getChildren(parentPath);
        System.out.println("children ======" + children);

        Thread.sleep(1000);
        zkClient.delete(parentPath + "/c1");
        Thread.sleep(1000);
        zkClient.delete(parentPath);
        Thread.sleep(Integer.MAX_VALUE);
        //zkClient.createPersistent("/zk-book/zlx", "123456");
        //创建节点，支持递归创建节点
        //zkClient.createPersistent(path,true);
    }

    public static ZkClient connectZK() {

        zkClient = new ZkClient(connectStr, sessionTime);
        System.out.println("Establish zkClient");
        return zkClient;
    }

    static class ChildrenChangesListener implements IZkChildListener {

        public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception {
            System.out.println(parentPath + " 's children changed, currentChildren are: " + currentChildren);

        }
    }


    static class ChildrenDataChangeListener implements IZkDataListener{

        //节点数据变化
        public void handleDataChange(String s, Object o) throws Exception {

            System.out.println("NOde " + s + " changed, new data is: " + o);
        }

        //删除节点
        public void handleDataDeleted(String s) throws Exception {
            System.out.println("Node " + s + " deleted;");
        }
    }

}
